package com.yc.meeting_attendance;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.hardware.Camera;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.IdRes;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Gallery;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.google.gson.reflect.TypeToken;
import com.hwangjr.rxbus.RxBus;
import com.yc.meeting_attendance.adapter.AttendanceAdapter;
import com.yc.meeting_attendance.adapter.Gallery_adapter;
import com.yc.meeting_attendance.adapter.ReGallery_adapter;
import com.yc.meeting_attendance.entity.Attachment;
import com.yc.meeting_attendance.entity.AttendanceResutl;
import com.yc.meeting_attendance.entity.CardEntity;
import com.yc.meeting_attendance.entity.ImageResutl;
import com.yc.meeting_attendance.entity.MeetingCheck;
import com.yc.meeting_attendance.entity.MeetingResutl;
import com.yc.meeting_attendance.entity.PersonnelResutl;
import com.yc.meeting_attendance.entity.Resutl;
import com.yc.meeting_attendance.fragment.SetDiagFragment;
import com.yc.meeting_attendance.net.AbsAPICallback;
import com.yc.meeting_attendance.net.Api;
import com.yc.meeting_attendance.utils.DatetimeUtil;
import com.yc.meeting_attendance.utils.DisplayUtil;
import com.yc.meeting_attendance.utils.MarqueeTextView;
import com.yc.meeting_attendance.utils.MyFileUtils;
import com.yc.meeting_attendance.utils.MyFunc;
import com.yc.meeting_attendance.utils.RealmHelper;
import com.yc.meeting_attendance.utils.SerialHelper;
import com.yc.meeting_attendance.utils.SharePreferenceUtil;
import com.yc.meeting_attendance.utils.ThreadUtil;
import com.yc.meeting_attendance.utils.sortClass;
import com.yc.meeting_attendance.wideget.SignDialog;
import com.yc.nfc.ComBean;
import com.yc.utilslib.reader.Licence;
import com.yc.utilslib.reader.Reader;
import com.yc.utilslib.reader.card.UserCard;
import com.yc.utilslib.reader.protocol.Cmd;
import com.yc.utilslib.reader.protocol.Command;
import com.yc.utilslib.reader.protocol.tagvalue.FTag;
import com.yc.utilslib.reader.protocol.tagvalue.Field;
import com.yc.utilslib.utils.DateUtils;
import com.yc.utilslib.utils.EncryptUtils;
import com.yc.utilslib.utils.GZipUtils;
import com.yc.utilslib.utils.StringUtils;

import java.nio.charset.Charset;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Timer;
import java.util.TimerTask;

import io.realm.RealmResults;
import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;
import rx.Subscriber;

import static com.yc.meeting_attendance.utils.DatetimeUtil.getSysDate;

public class TestMainActivity extends Activity implements View.OnClickListener {
    private static final String TAG = TestMainActivity.class.getSimpleName();
    private TextView tiem;
    private TextView week;
    private TextView date;
    private ImageView set;
    private TextView place;
    Intent intent1;
    SurfaceView preview;
    private Camera mCamera;
    SurfaceHolder mSurfaceHolder;
    private ViewGroup mMoreLayout, mMoreLayouts, mMoreLayoutss;
    LinearLayout linearLayout;
    ViewGroup.LayoutParams layoutParams;
    GridView listView;
    RealmHelper realmHelper = new RealmHelper(this);
    List<MeetingCheck> list1 = new ArrayList<>();
    List<String> MeetingId = new ArrayList<>();
    List<String> BigenCard = new ArrayList<>();
    List<String> EndCard = new ArrayList<>();
    List<String> ImgaViewIndex = new ArrayList<>();
    List<List<String>> ImgaView = new ArrayList<>();
    List<Integer> mListR = new ArrayList<Integer>();
    TextView practical;
    int indexBigen;
    int indexEnd;
    int realized = 0;
    SoundPool soundPool = null;
    SoundPool soundPool1 = null;
    SoundPool soundPool2 = null;
    int sourceid = 0;
    int failure = 0;
    int credit = 0;
    boolean isSoundReady;
    boolean subscript;
    List<PersonnelResutl> list = new ArrayList<>();
    AttendanceAdapter attendanceAdapter;
    ReGallery_adapter reGllery;
    Gallery main_gallery;
    LinearLayout main_lin;
    Gallery_adapter gallery_adapter;
    int current_circle = 0;
    Runnable timeadv;
    int count;
    GifImageView imgview;
    List<String> li = new ArrayList<String>();
    private SharePreferenceUtil mSharePreferenceUtil;
    Timer timerImgView;
    TimerTask taskImgView;

    LinearLayout layout_more1;


    private boolean isReStart;//是否重启
    ProgressDialog MyDialog;
    Activity myActivity;


    private boolean isLoading = false; //是否正在上传中

    int DST_RECT_WIDTH, DST_RECT_HEIGHT;//矩形拍照尺寸
    Point rectPictureSize = null;
    int DST_CENTER_RECT_WIDTH = 280; //单位是dip
    int DST_CENTER_RECT_HEIGHT = 280;//单位是dip
    SignDialog signDialog;
    MeetingResutl meetingResutl;



    //
    String licence;
    Reader mReader;
    private Queue<String> mMsgQueue = new LinkedList<>();

    private Handler mUIHandler = new Handler() {

        Date lastDate = new Date(System.currentTimeMillis());
        long lastCard = 0;

        @Override
        public void handleMessage(Message msg) {
            Command cmd = (Command) msg.obj;

            switch (cmd.getCmd()) {
                case SET_TIME:
                    break;
                case GET_TIME:
                    break;
                case SET_PARA:
                    ShowMsg(FTag.SYS_CMD_RET, cmd);
                    break;
                case GET_PARA:
                    ShowMsg(FTag.SYS_CMD_RET, cmd);
                    break;
                case FIND_CARD:
                    break;
                case ANTI:
                    break;
                case SELECT:
                    break;
                case AUTHENTICATION:
                    ShowMsg(FTag.SYS_CMD_RET, cmd);
                    break;
                case BLOCK_READ:
                    break;
                case BLOCK_WRITE:
                    break;
                case SECTOR_READ:
                    break;
                case SECTOR_WRITE:
                    break;
                case HALT:
                    break;
                case READ_CARD:
                    ShowMsg(FTag.CARD_PARA_SERIAL_NO, cmd);
                    break;
                case CONSUME:
                    break;
                case SEND_CARD_ID:
                    ShowMsg(FTag.CARD_PARA_ID, cmd);
                    break;
                case SEND_CARD_INFO:
                    Date curDate = new Date(System.currentTimeMillis());
                    long time = curDate.getTime() - lastDate.getTime();
                    long curCard = lastCard;
                    long curSerial_No = 0;
                    UserCard card = null;
                    if (cmd.getFieldArray().containsKey(FTag.CARD_PARA_ID)) {
                        curCard = (long) cmd.getFieldArray().get(FTag.CARD_PARA_ID).getValue();
                        card = UserCard.getInstance(cmd.getFieldArray().get(FTag.CARD_PARA_ID).getBytes(),
                                new byte[16], new byte[16], new byte[16]);
                    }
                    if (cmd.getFieldArray().containsKey(FTag.CARD_PARA_SERIAL_NO)) {
                        curSerial_No = (long) cmd.getFieldArray().get(FTag.CARD_PARA_SERIAL_NO).getValue();

                    }
                    mMsgQueue.add("----------------------------------------------------");
                    ShowMsg(FTag.SYS_CMD_RET, cmd);
                    ShowMsg(FTag.CARD_PARA_ID, cmd);
                    ShowMsg(FTag.CARD_PARA_SERIAL_NO, cmd);
                    ShowMsg(FTag.CARD_PARA_TYPE, cmd);
                    ShowMsg(FTag.CARD_PARA_EXCESS_KEY, cmd);
                    ShowMsg(FTag.CARD_PARA_STOP_DATE, cmd);
                    ShowMsg(FTag.CARD_PARA_REST_MONEY, cmd);
                    ShowMsg(FTag.CARD_PARA_USED_MONEY, cmd);
                    ShowMsg(FTag.CARD_PARA_CONSUME_TIME, cmd);
                    ShowMsg(FTag.CARD_PARA_TOTAL_USED_TIMES, cmd);
                    ShowMsg(FTag.CARD_PARA_TOTAL_USED_MONEY, cmd);
                    ShowMsg(FTag.CARD_PARA_NAME, cmd);

                    if (cmd.getFieldArray().containsKey(FTag.CARD_PARA_NAME)) {
                        card.setExtendedInfo((byte[]) cmd.getFieldArray().get(FTag.CARD_PARA_NAME).getValue());

                        mMsgQueue.add("EmpName:" + card.getExtendedInfo().getEmployeeName());
                        mMsgQueue.add("EmpStrID:" + card.getExtendedInfo().getEmployeeStrId());
                        mMsgQueue.add("CardType:" + card.getExtendedInfo().getCardType());
                    }

                    Log.e("wwwww", "Time:" + (time > 10) + "lastCard != curCard:" + (lastCard != curCard));
                    if (time > 2500 || lastCard != curCard) {
                        if (cmd.getFieldArray().containsKey(FTag.SYS_CMD_RET)) {
                            if (((int) cmd.getFieldArray().get(FTag.SYS_CMD_RET).getValue()) == 0) {
                                lastCard = curCard;
                                Log.e("wwwww", DateUtils.YYYYMMDDHHMMSS_SHORT.format(new Date(System.currentTimeMillis())) + "lastCard=" + lastCard + "卡流水：curSerial_No=" + curSerial_No);
                                CardEntity mCard = new CardEntity();
                                mCard.cardFixId = String.valueOf(lastCard);
                                mCard.cardSerial = String.valueOf(curSerial_No);

                                if (cmd.getFieldArray().containsKey(FTag.CARD_PARA_NAME)) {
                                    card.setExtendedInfo((byte[]) cmd.getFieldArray().get(FTag.CARD_PARA_NAME).getValue());
                                    mCard.mEmployeeStrId = card.getExtendedInfo().getEmployeeStrId();
                                    Log.e("www", "mCard.mEmployeeStrId=" + mCard.mEmployeeStrId);

                                }else{
                                    mCard.mEmployeeStrId="0";
                                }
                            } else {
                                lastCard = curCard;
                                Log.e("wwwww","只取物理卡号--"+ DateUtils.YYYYMMDDHHMMSS_SHORT.format(new Date(System.currentTimeMillis())) + "lastCard=" + lastCard + "卡流水：curSerial_No=" + curSerial_No);

                            }
                            if(lastCard!=0){//说明有物理卡号
                                doExecCard(lastCard+"");
                            }else{
                                soundPool1.play(1, 1, 1, 0, 0, 1);
                            }

                        } else {
                            soundPool1.play(1, 1, 1, 0, 0, 1);
                            return;
                        }



                        lastDate = curDate;
                        lastCard = curCard;
                    }
                    break;
            }

      /*      int index = mMsgQueue.size();
        *//*    Date curDate = new Date(System.currentTimeMillis());
            long time = curDate.getTime() - lastDate.getTime();*//*
            if(lastCard!=0){
                Log.e("wwwww", DateUtils.YYYYMMDDHHMMSS_SHORT.format(new Date(System.currentTimeMillis()))+"lastCard="+lastCard);
                soundPool.play(1, 1, 1, 0, 0, 1);
            }else{
                soundPool1.play(1, 1, 1, 0, 0, 1);
                Log.e("wwwww","lastCard==0");
            }*/


            //获取

            // mTextViewShow.setText(null);
         /*   int index = mMsgQueue.size();
            for (int i = index; i > 0 ; i--) {
                String value = mMsgQueue.poll();
                Log.e("www",value+"\r\n");
               // mTextViewShow.append(value + "\r\n");
                if (i < 20) {
                    mMsgQueue.add(value);
                }
            }*/
        }

        private void ShowMsg(FTag tag, Command cmd) {
            if (cmd.getFieldArray().containsKey(tag)) {
                mMsgQueue.add(DateUtils.YYYYMMDDHHMMSS_SHORT.format(new Date(System.currentTimeMillis())) + " : " +
                        cmd.getCmd().getName() + " | " +
                        cmd.getFieldArray().get(tag).toString());
            }
        }
    };

    private Handler mReaderErrorHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            mReader.restart();
        }
    };

    //
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myActivity = this;
        // 隐藏标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);
        RxBus.get().register(this);
//        intent1 = new Intent(this, CheckCardExistService.class);
//        startService(intent1);
        mSharePreferenceUtil = MyApp.getsInstance().sharePreferenceUtil;

        mListR.add(1);
        mListR.add(2);
        mListR.add(3);

        setView();
        setTiem();
        message();
        personnel();
        SetImagView();

        //定时器
        Timer timerCard = new Timer();
        TimerTask tastCard = new TimerTask() {
            @Override
            public void run() {
                if (MyApp.getsInstance().getgiDestPort() == 1) {
                    MyApp.getsInstance().setCard("1");
                }


            }
        };
        timerCard.schedule(tastCard, 1000, 1000);

        //1：下载licence 2：发送设置指令
        doReadCardSetting();

    }

    private void doReadCardSetting() {
        int com = MyApp.getsInstance().sharePreferenceUtil.getCom();
        mReader = new Reader("/dev/ttyS" + com, 115200);
        mReader.setmHandlerError(mReaderErrorHandler);
        if (!mReader.open(mUIHandler)) {
            Log.w("www", "读卡器打开失败！！！");
        } else {
            //由于测试设备无法联网，只能指定lic的值
            if (StringUtils.isNullOrEmpty(licence)) {
                licence = "H4sIAAAAAAAACwGAAH//l5t20s5NefgiFEh0YvA0/0BH7GbOvxRhYSxUeJYyJ8gtN5p5IAc00IAYrziMjpiiVmZcwMeFPPJHb9VkQhlg6MDu1Tdl7i2ZqsBPdz+mHpsAXVo7xFARqUbKkuizUDCnPyyPAEbLb9p+SsYTg/SVUj7wzsxUPf2IHa6OuqPWWugCv3q2gAAAAA==";

                if (loadLicence(licence)) {
                    Map<FTag, Field> para = new HashMap<>();
                    para.put(FTag.SYS_WORK_MODE,
                            Field.getInstance(FTag.SYS_WORK_MODE, 0x00));
                    para.put(FTag.SYS_COMM_MODE,
                            Field.getInstance(FTag.SYS_COMM_MODE, 0x00));
                    para.put(FTag.SYS_PARA_XF_SECTOR,
                            Field.getInstance(FTag.SYS_PARA_XF_SECTOR, Licence.getInstance().getXfxt_sec()));
                    para.put(FTag.SYS_PARA_SK_SECTOR,
                            Field.getInstance(FTag.SYS_PARA_SK_SECTOR, Licence.getInstance().getJsxt_sec()));
                    para.put(FTag.SYS_READ_MODE,
                            Field.getInstance(FTag.SYS_READ_MODE, 1));
                    para.put(FTag.CARD_PARA_AUTH_TYPE,
                            Field.getInstance(FTag.CARD_PARA_AUTH_TYPE, 0x60));
                    para.put(FTag.SYS_PARA_KEY_A,
                            Field.getInstance(FTag.SYS_PARA_KEY_A, Licence.getInstance().getOprater_password()));
                    para.put(FTag.SYS_PARA_KEY_B,
                            Field.getInstance(FTag.SYS_PARA_KEY_B, Licence.getInstance().getKeyB()));
                    para.put(FTag.SYS_MACHINE_NO,
                            Field.getInstance(FTag.SYS_MACHINE_NO, 0x0001));
                    Command auth = new Command(Cmd.SET_PARA, para);
                    mReader.SetCommand(auth);

                }
            }
        }
    }
        /**
         * 加载Lic信息
         *
         * @param licence Lic数据
         * @return 是否成功
         */
    private boolean loadLicence(String licence) {
        byte[] decData = GZipUtils.decompressForGzip(licence);
        Licence.fromData(EncryptUtils.AES.decrypt(decData,
                "y&c@sz^%,.r#T*!~".getBytes(Charset.forName("ASCII"))));

        return Licence.getInstance().getXfxt_sec() > 0;
    }

    private void setTiem() {
        tiem = getView(R.id.tiem);
        week = getView(R.id.week);
        date = getView(R.id.date);
        SetData(tiem);
        week.setText("星期" + DatetimeUtil.getWhere());
        date.setText(getSysDate("yyyy年MM月dd日"));
        new Thread(new MyThread()).start();
    }

    private void message() {
    }

    private void personnel() {
    }

    private void SetImagView() {
        MarqueeTextView autoText = getView(R.id.autoText);
        autoText.setFocusable(true);
        autoText.setFocusableInTouchMode(true);
        autoText.setText(getResources().getString(R.string.tx_welcome_Title));
        main_gallery = getView(R.id.main_gallery);
        main_lin = getView(R.id.main_lin);
        preview = getView(R.id.preview);
        mSurfaceHolder = preview.getHolder();
        mSurfaceHolder.addCallback(new SufaceListener());
        mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        mSurfaceHolder.setFixedSize(1920, 1080); //设置分辨率 640, 480
        imgview = (GifImageView) getView(R.id.imgview);
        //initGallery_adapter();
//        main_gallery.setAdapter(gallery_adapter);
        initReGllery();
        setCircle();
        main_gallery.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {

                return false;
            }
        });


        //设置滚动图片的时候，对应小圆点的图片切换
        main_gallery.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                View v = main_lin.getChildAt(position);
                View cuview = main_lin.getChildAt(current_circle);

                if (v != null && cuview != null) {
                    ImageView pointView = (ImageView) v;
                    ImageView curpointView = (ImageView) cuview;
                    curpointView
                            .setBackgroundResource(R.mipmap.pink);
                    pointView
                            .setBackgroundResource(R.mipmap.red);
                    current_circle = position;
                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        //
        timeadv = new Runnable() {

            @Override
            public void run() {
                //获取当前的图片是哪一张图片，图片的序号，
                count = main_gallery.getSelectedItemPosition();
                //当前滚动的图片序号大于多有的图片的数量，就跳转到第一张图片，否则就跳转到下一张图片
                if (null != li && li.size() > 1) {
                    if (count + 1 >= li.size()) {
                        count = 0;
                    } else {
                        count = count + 1;
                    }
                } else {
                    if (count + 1 >= mListR.size()) {
                        count = 0;
                    } else {
                        count = count + 1;
                    }
                }
                main_gallery.setSelection(count);
                handler.postDelayed(this, 2500);

            }
        };

        //开始定时器，1000毫秒切换一次图片5
        handler.postDelayed(timeadv, 2500);

    }


    private void setView() {

        place = getView(R.id.place);
        set = getView(R.id.set);
        set.setOnClickListener(this);
        place.setText(mSharePreferenceUtil.getClassId());
        listView = getView(R.id.listview);
        practical = getView(R.id.num);
        loadMusic();
        practical.setText("0/0/0");
        layout_more1 = getView(R.id.layout_more1);
        setupViews(R.layout.layout_depar, R.layout.layout_department, R.id.layout_more, R.id.layout_more1, R.id.tiee, realmHelper.QueryAll());

        timer.schedule(task, 1000, 1000);

        //定时器
        Timer timerCard = new Timer();
        TimerTask tastCard = new TimerTask() {
            @Override
            public void run() {
                if (MyApp.getsInstance().getgiDestPort() == 1)
                    MyApp.getsInstance().setCard("1");

                Log.d("TAG", "card:" + MyApp.getsInstance().getCard());

            }
        };
        timerCard.schedule(tastCard, 1000, 1000);


    }


    private void GetClass() {
        Api.getInstance().GetMeeting(new AbsAPICallback<AttendanceResutl>(this) {

            @Override
            public void onCompleted() {
                Log.e("TAG", "comple---");
            }

            @Override
            public void onNext(AttendanceResutl attendanceResutl) {
                Log.e("TAG", "onNext---");
                mSharePreferenceUtil.setFig(false);
                realmHelper.deleteDogAll(MeetingResutl.class);
                realmHelper.deleteDogAll(PersonnelResutl.class);
                realmHelper.deleteDogAll(MeetingCheck.class);
                realmHelper.deleteDogAll(Attachment.class);
                MyFileUtils.deleteFile(MyFileUtils.mListAttachUrl);
                Log.e("TAG", "attendanceResutl:" + attendanceResutl.getMeeting().size());
                if (attendanceResutl.isCode()) {
                    if (null != attendanceResutl.getMeeting()) {
                        mSharePreferenceUtil.setClassId(attendanceResutl.getMeeting().get(0).getRoomName());
                        for (int i = 0; i < attendanceResutl.getMeeting().size(); i++) {
                            BigenCard.add(attendanceResutl.getMeeting().get(i).getBeginTime());
                            EndCard.add(attendanceResutl.getMeeting().get(i).getEndTime());
                            MeetingId.add(attendanceResutl.getMeeting().get(i).getUuid());


                        }
                        ThreadUtil.getInstance().submit(new Runnable() {
                            @Override
                            public void run() {

                                MyFileUtils.deleteFile(MyFileUtils.MeetingId);
                                MyFileUtils.deleteFile(MyFileUtils.BigenCard);
                                MyFileUtils.deleteFile(MyFileUtils.EndCard);
                                MyFileUtils.deleteFile(MyFileUtils.mListAttachUrl);

                                MyFileUtils.saveObject2File(MeetingId, MyFileUtils.MeetingId);
                                MyFileUtils.saveObject2File(BigenCard, MyFileUtils.BigenCard);
                                MyFileUtils.saveObject2File(EndCard, MyFileUtils.EndCard);
                                MyFileUtils.saveObject2File(li, MyFileUtils.mListAttachUrl);
                                Log.d(TAG, "默认保存 缓存数据-PersonnelResutl-");


                            }
                        });

//                        mSharePreferenceUtil.setAdvance(attendanceResutl.getCheckrule().getInBefore());
//                        mSharePreferenceUtil.setBeLatee(attendanceResutl.getCheckrule().getBeLate());
//                        mSharePreferenceUtil.setAbsenteeisn(attendanceResutl.getCheckrule().getAbsenteeism());
//                        mSharePreferenceUtil.setNeedCheckout(attendanceResutl.getCheckrule().getNeedCheckout());
//                        mSharePreferenceUtil.setoutBefore(attendanceResutl.getCheckrule().getOutBefore());
//                        mSharePreferenceUtil.setleaveEalryint(attendanceResutl.getCheckrule().getLeaveEarly());
//                        mSharePreferenceUtil.setOutLate(attendanceResutl.getCheckrule().getOutLate());


                        for (int i = 0; i < attendanceResutl.getMeeting().size(); i++) {
                            MeetingResutl meetingResutl = new MeetingResutl();
                            meetingResutl.setBegin(attendanceResutl.getMeeting().get(i).getBeginTime());
                            meetingResutl.setEnd(attendanceResutl.getMeeting().get(i).getEndTime());
                            meetingResutl.setUuid(attendanceResutl.getMeeting().get(i).getUuid());
                            meetingResutl.setMeetingName(attendanceResutl.getMeeting().get(i).getMeetingName());
                            meetingResutl.setEmcee(attendanceResutl.getMeeting().get(i).getEmcee());
                            meetingResutl.setMeetingId(attendanceResutl.getMeeting().get(i).getUuid());
                            meetingResutl.setInBefore(attendanceResutl.getMeeting().get(i).getOaMeetingcheckrule().getInBefore());
                            meetingResutl.setBeLate(attendanceResutl.getMeeting().get(i).getOaMeetingcheckrule().getBeLate());
                            meetingResutl.setNeedCheckout(attendanceResutl.getMeeting().get(i).getOaMeetingcheckrule().getNeedCheckout());
                            meetingResutl.setAbsenteeism(attendanceResutl.getMeeting().get(i).getOaMeetingcheckrule().getAbsenteeism());
                            meetingResutl.setOutBefore(attendanceResutl.getMeeting().get(i).getOaMeetingcheckrule().getOutBefore());
                            meetingResutl.setLeaveEarly(attendanceResutl.getMeeting().get(i).getOaMeetingcheckrule().getLeaveEarly());
                            meetingResutl.setOutLate(attendanceResutl.getMeeting().get(i).getOaMeetingcheckrule().getOutLate());
                            if (null == attendanceResutl.getMeeting().get(i).getExtField05()) {
                                meetingResutl.setExtField05("0");
                            } else {
                                meetingResutl.setExtField05((String) attendanceResutl.getMeeting().get(i).getExtField05());
                            }

                            realmHelper.addDog(meetingResutl);

                            if (attendanceResutl.getMeeting().get(i).getAttachment() != null && attendanceResutl.getMeeting().get(i).getAttachment().size() != 0) {
                                for (int j = 0; j < attendanceResutl.getMeeting().get(i).getAttachment().size(); j++) {
                                    Attachment attachment = new Attachment();
                                    attachment.setMeetingId(attendanceResutl.getMeeting().get(i).getMeetingemp().get(j).getMeetingId());
                                    attachment.setAttachName(attendanceResutl.getMeeting().get(i).getAttachment().get(j).getAttachName());
                                    attachment.setAttachUrl(mSharePreferenceUtil.getServerAddress() + attendanceResutl.getMeeting().get(i).getAttachment().get(j).getAttachUrl());
                                    realmHelper.addDog(attachment);


                                }
                            }

                        }

                        for (int i = 0; i < attendanceResutl.getMeeting().size(); i++) {
                            for (int j = 0; j < attendanceResutl.getMeeting().get(i).getMeetingemp().size(); j++) {
                                PersonnelResutl personnelResutl = new PersonnelResutl();
                                personnelResutl.setUuid(attendanceResutl.getMeeting().get(i).getMeetingemp().get(j).getUuid());
                                personnelResutl.setXm(attendanceResutl.getMeeting().get(i).getMeetingemp().get(j).getXm());
                                personnelResutl.setCardNo(attendanceResutl.getMeeting().get(i).getMeetingemp().get(j).getCardNo() + "");
                                personnelResutl.setType(0);
                                personnelResutl.setTime("00:00:00");
                                personnelResutl.setInResult("4");
                                personnelResutl.setOutResult(null);
                                personnelResutl.setAttendResult("4");
                                personnelResutl.setWlkh(attendanceResutl.getMeeting().get(i).getMeetingemp().get(j).getFactoryfixId() + "");
                                personnelResutl.setMeetingId(attendanceResutl.getMeeting().get(i).getMeetingemp().get(j).getMeetingId());
                                personnelResutl.setUserId(attendanceResutl.getMeeting().get(i).getMeetingemp().get(j).getUuid());
                                personnelResutl.setLg("0");
                                personnelResutl.setIsLeave(attendanceResutl.getMeeting().get(i).getMeetingemp().get(j).getIsLeave());
                                realmHelper.addDog(personnelResutl);
                            }


                        }
                    } else {//网络通 无 信息会议
                        List<MeetingResutl> mlist = new ArrayList<>();
                        setupViews(R.layout.layout_depar, R.layout.layout_department, R.id.layout_more, R.id.layout_more1, R.id.tiee, mlist);

                    }
                    indexBigen = 0;
                    indexEnd = 0;
                    mSharePreferenceUtil.setIndexBigen(0);
                    mSharePreferenceUtil.setIndexEnd(0);
                    MyApp.getsInstance().setMeetingId(MeetingId);
                    MyApp.getsInstance().setBigenCard(BigenCard);
                    MyApp.getsInstance().setEndCard(EndCard);


                    place.setText(attendanceResutl.getMeeting().get(0).getRoomName());
                    setupViews(R.layout.layout_depar, R.layout.layout_department, R.id.layout_more, R.id.layout_more1, R.id.tiee, realmHelper.QueryAll());

                /*    li.clear();
                    for (int i = 0; i < realmHelper.QueryImag(MeetingId.get(mSharePreferenceUtil.getIndexBigen())).size(); i++) {
                        Attachment attachment = ((Attachment) realmHelper.QueryImag(MeetingId.get(mSharePreferenceUtil.getIndexBigen())).get(i));
                        li.add(attachment.getAttachUrl());
                    }
//                    Log.d("TAG","url:"+attachment.getAttachUrl());
                    Log.d("TAG", "li:" + li.size());
                    if (li.size() != 0) {
//                        gallery_adapter.setList(li);
                        initGallery_adapter();
                        setCircle();
                    }*/

                    Log.d("TAG", "QueryAll:" + realmHelper.QueryAll().size());
                } else {
                    Log.d("TAG", "mmmmm" + attendanceResutl.getMessage());

                }
            }

            //
            @Override
            public void onError(Throwable e) {

                super.onError(e);
                if (null != e) {
                    Log.e("TAG", "e：" + e.getMessage());
                } else {
                    Log.e("TAG", "e：=null");
                }


            }


        }, mSharePreferenceUtil.getEquipment(), getSysDate("yyyy-MM-dd HH:mm:ss"));


        //取现在时间
    }

    private void doAPPChange() {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        //知道要跳转应用的包名、类名
        ComponentName componentName = new ComponentName("com.yc.class_attendance", "com.yc.class_attendance.ReMainActivity");
        intent.setComponent(componentName);
        startActivity(intent);
        doClearDataReStart();
    }

    //设置滚动图片的小圆点
    private void setCircle() {
        main_lin.removeAllViews();
        ImageView iv = null;
        for (int i = 0; i < li.size(); i++) {
            iv = new ImageView(TestMainActivity.this);
            //循环创建小圆点，判断第一个小圆点为白色的，其他的都是透明的
            if (i == 0) {
                iv.setBackgroundResource(R.mipmap.red);
            } else {
                iv.setBackgroundResource(R.mipmap.pink);
            }

            main_lin.addView(iv);

            //设置小圆点的margin值
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1);  // , 1�ǿ�ѡд��
            lp.setMargins(5, 10, 5, 10);
            iv.setLayoutParams(lp);

        }
    }

    private void setupViews(int layout1, int layout2, int layout3, int layout4, int layout5, List<MeetingResutl> list) {

        mMoreLayout = getView(layout3);   //找到该容器（这里的控件为LinearLayout，转换为ViewGroup是因为ViewGroup是容器的基类）
        mMoreLayouts = getView(layout4);
        mMoreLayoutss = getView(layout5);
        mMoreLayout.removeAllViews();
        mMoreLayouts.removeAllViews();
        mMoreLayoutss.removeAllViews();

        /**
         * 由于文字也是动态生成，这里用数组比较多余，使用android中array文件定义资源文件，并取出(便于管理，文字和代码分开，日后要修改直接找资源数组文件便可，不用找代码)
         */
//        final String[] categories = {""};
        final String[] categoriess = {"主题", "时间", "主持人"};


        /**
         * 动态添加布局方法封装
         * 参数 1.父容器    2.资源文字数组  3.从第几个开始   4.行数
         */
        if (list.size() != 0) {
            // fillView(mMoreLayout, list, layout2);
            //fillViews(mMoreLayout, list, layout2);
            fillView(mMoreLayout, mMoreLayouts, list, layout2);
        }
//        fillViewsOne(mMoreLayouts, categories, layout1);
        fillViewsOne(mMoreLayoutss, categoriess, layout1);

    }

    public void fillViews(ViewGroup layout, List<MeetingResutl> list, int lone) {
        String firstCategory = null;
        String secondCategory = null;
        String thirdCategory = null;
        Log.d("TAG", "size:" + list.size());
        for (int i = 0; i < 3; i++) {
            if (list.size() == 1) {
                if (i == 0) {
                    firstCategory = list.get(0).getMeetingName();
                } else if (i == 1) {
                    firstCategory = DatetimeUtil.gethour(list.get(0).getBegin()) + " - " + DatetimeUtil.gethour(list.get(0).getEnd());
                }
                if (i == 2) {
                    firstCategory = list.get(0).getEmcee();
                }

            } else if (list.size() == 2) {
                if (i == 0) {
                    firstCategory = list.get(0).getMeetingName();
                    secondCategory = list.get(0).getMeetingName();

                } else if (i == 1) {
                    firstCategory = DatetimeUtil.gethour(list.get(0).getBegin()) + " - " + DatetimeUtil.gethour(list.get(0).getEnd());
                    secondCategory = DatetimeUtil.gethour(list.get(1).getBegin()) + " - " + DatetimeUtil.gethour(list.get(1).getEnd());
                }
                if (i == 2) {
                    firstCategory = list.get(0).getEmcee();
                    secondCategory = list.get(1).getEmcee();
                }

            } else if (list.size() == 3) {
                if (i == 0) {
                    firstCategory = list.get(0).getEmcee();
                    secondCategory = list.get(1).getEmcee();
                    thirdCategory = list.get(2).getEmcee();
                } else if (i == 1) {
                    firstCategory = list.get(0).getMeetingName();
                    secondCategory = list.get(1).getMeetingName();
                    thirdCategory = list.get(2).getMeetingName();
                }
                if (i == 2) {
                    firstCategory = list.get(0).getMeetingName();
                    secondCategory = list.get(1).getMeetingName();
                    thirdCategory = list.get(2).getMeetingName();
                }


            }

            linearLayout = new LinearLayout(this);

            // 表格第一条线
            View.inflate(this, R.layout.layout_line_horizonal, layout);
            View.inflate(this, R.layout.layout_line_vertical, linearLayout);
            // 第一个子布局
            View.inflate(this, lone, linearLayout);
            View.inflate(this, R.layout.layout_line_vertical, linearLayout);
            // 第二个子布局
            View.inflate(this, lone, linearLayout);
            View.inflate(this, R.layout.layout_line_vertical, linearLayout);

            // 第三个子布局
            View.inflate(this, lone, linearLayout);
            View.inflate(this, R.layout.layout_line_vertical, linearLayout);

            layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            layout.addView(linearLayout, layoutParams);

            // 表格最后一条线
            View.inflate(this, R.layout.layout_line_horizonal, layout);

            //根据索引getChildAt到指定的位置
            final View firstView = linearLayout.getChildAt(1);
            firstView.setTag(firstCategory);        //设置tag，便于在后面判断点击的哪一个
            final TextView firstTextView = (TextView) firstView.findViewById(R.id.text_title);
            firstTextView.setText(firstCategory);   //设置文字


            final View secondView = linearLayout.getChildAt(3);
            secondView.setTag(secondCategory);
            final TextView secondTextView = (TextView) secondView.findViewById(R.id.text_title);
            secondTextView.setText(secondCategory);

            final View thirdView = linearLayout.getChildAt(5);
            thirdView.setTag(thirdCategory);
            final TextView thirdTextView = (TextView) thirdView.findViewById(R.id.text_title);
            thirdTextView.setText(thirdCategory);

        }


    }

    String firstCategory;

    public void fillView(ViewGroup layout, ViewGroup layout1, List<MeetingResutl> list, int lone) {
        if (list.size() > 0) {
            for (int i = 0; i < 3; i++) {
                //找到索引，便于根据索引添加图片文件和文字

                if (i == 0) {
                    firstCategory = list.get(0).getMeetingName();
                } else if (i == 1) {
                    firstCategory = DatetimeUtil.gethour(list.get(0).getBegin()) + " - " + DatetimeUtil.gethour(list.get(0).getEnd());
                }
                if (i == 2) {
                    firstCategory = list.get(0).getEmcee();
                }
                linearLayout = new LinearLayout(this);

                // 表格第一条线
                View.inflate(this, R.layout.layout_line_horizonal, layout);
                // 第一个子布局
                View.inflate(this, R.layout.layout_line_vertical, linearLayout);
                View.inflate(this, lone, linearLayout);
                View.inflate(this, R.layout.layout_line_vertical, linearLayout);

                layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                layout.addView(linearLayout, layoutParams);
                // 表格最后一条线
                View.inflate(this, R.layout.layout_line_horizonal, layout);

                //根据索引getChildAt到指定的位置
                final View firstView = linearLayout.getChildAt(1);
                firstView.setTag(firstCategory);        //设置tag，便于在后面判断点击的哪一个
                final TextView firstTextView = (TextView) firstView.findViewById(R.id.text_title);
                firstTextView.setText(firstCategory);   //设置文字
                layout_more1.setVisibility(View.GONE);
            }
        }
        if (list.size() == 2) {
            for (int i = 0; i < 3; i++) {
                //找到索引，便于根据索引添加图片文件和文字
                layout_more1.setVisibility(View.VISIBLE);
                if (i == 0) {
                    firstCategory = list.get(1).getMeetingName();
                } else if (i == 1) {
                    firstCategory = DatetimeUtil.gethour(list.get(1).getBegin()) + " - " + DatetimeUtil.gethour(list.get(1).getEnd());
                }
                if (i == 2) {
                    firstCategory = list.get(1).getEmcee();
                }
                linearLayout = new LinearLayout(this);

                // 表格第一条线
                View.inflate(this, R.layout.layout_line_horizonal, layout1);
                // 第一个子布局
                View.inflate(this, R.layout.layout_line_vertical, linearLayout);
                View.inflate(this, lone, linearLayout);
                View.inflate(this, R.layout.layout_line_vertical, linearLayout);

                layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                layout1.addView(linearLayout, layoutParams);
                // 表格最后一条线
                View.inflate(this, R.layout.layout_line_horizonal, layout1);

                //根据索引getChildAt到指定的位置
                final View firstView = linearLayout.getChildAt(1);
                firstView.setTag(firstCategory);        //设置tag，便于在后面判断点击的哪一个
                final TextView firstTextView = (TextView) firstView.findViewById(R.id.text_title);
                firstTextView.setText(firstCategory);   //设置文字
            }
        }
    }

    public void fillViewsOne(ViewGroup layout, String[] categories, int lone) {
        for (int i = 0; i < categories.length; i++) {
            //找到索引，便于根据索引添加图片文件和文字
            String firstCategory = categories[i];
            linearLayout = new LinearLayout(this);
            // 表格第一条线
            View.inflate(this, R.layout.layout_line_horizonal, layout);
            // 第一个子布局
            View.inflate(this, R.layout.layout_line_vertical, linearLayout);
            View.inflate(this, lone, linearLayout);
            View.inflate(this, R.layout.layout_line_vertical, linearLayout);

            layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            layout.addView(linearLayout, layoutParams);

            // 表格最后一条线
            View.inflate(this, R.layout.layout_line_horizonal, layout);

            //根                                               据索引getChildAt到指定的位置
            final View firstView = linearLayout.getChildAt(1);
            firstView.setTag(firstCategory);        //设置tag，便于在后面判断点击的哪一个
            final TextView firstTextView = (TextView) firstView.findViewById(R.id.text_title);
            firstTextView.setText(firstCategory);   //设置文字
        }
    }


    private void UploadImage(String base64, String wlkh, String Userid) {

        Subscriber<ImageResutl> subscriber = new AbsAPICallback<ImageResutl>(this) {
            @Override
            public void onNext(ImageResutl imageResutl) {
                Log.d("TAG", "resutl:" + imageResutl.getMessage());
                Log.d("TAG", "isCode:" + imageResutl.isCode());

            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);

            }
        };

        Api.getInstance().UploadImageString(subscriber, "OaMeeting", base64, wlkh, Userid);
    }

    void doShowDialog() {
        MyDialog = new ProgressDialog(this, R.style.dialog);
        MyDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        MyDialog.setCanceledOnTouchOutside(false);
        MyDialog.setMessage("上传中...");
        MyDialog.setCancelable(false);
        MyDialog.show();
    }

    Date startDate = null;
    long startTime = 0;

    private void takePicture(final String whik) {


        String mUserId = "";
        MeetingCheck dog = realmHelper.queryDogById(whik);
        if (null != dog) {
            mUserId = dog.getUserId();
        }
        startDate = new Date(System.currentTimeMillis());
        startTime = startDate.getTime();
        if (mCamera != null) {

            final String finalMUserId = mUserId;
            ThreadUtil.getInstance().submit(new Runnable() {
                @Override
                public void run() {
                    mCamera.autoFocus(null);
                    mCamera.setPreviewCallback(null);
                    mCamera.takePicture(null, null, new Camera.PictureCallback() {
                        @Override
                        public void onPictureTaken(byte[] bytes, Camera camera) {
                            Date curDate = new Date(System.currentTimeMillis());
                            long time = curDate.getTime() - startTime;
                            Log.e("www1", "抓拍返回时间：" + time);
                            if (rectPictureSize == null) {
                                rectPictureSize = createCenterPictureRect(DisplayUtil.dip2px(TestMainActivity.this, DST_CENTER_RECT_WIDTH)
                                        , DisplayUtil.dip2px(TestMainActivity.this, DST_CENTER_RECT_HEIGHT));
                                DST_RECT_WIDTH = rectPictureSize.x;
                                DST_RECT_HEIGHT = rectPictureSize.y;
                            }
                            final Bitmap bitmap = BitmapFactory.decodeByteArray
                                    (bytes, 0, bytes.length);//图片
                            Matrix matrix = new Matrix();
                            matrix.setRotate(90);
                            final Bitmap Newbm = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);

                          /*  int x = Newbm.getWidth() / 2 - DST_RECT_WIDTH / 2;
                            int y = Newbm.getHeight() / 2 - DST_RECT_HEIGHT / 2;*/
                            int x = Newbm.getWidth() / 2 - 200;
                            int y = Newbm.getHeight() / 2 - DST_RECT_HEIGHT / 2;
                            final Bitmap rectBitmap = Bitmap.createBitmap(Newbm, x, y, DST_RECT_HEIGHT, DST_RECT_HEIGHT);
                            final Bitmap imagBitmap = zoomImg(rectBitmap, 720, 700);


                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Date curDate1 = new Date(System.currentTimeMillis());
                                    long time1 = curDate1.getTime() - startTime;
                                    Log.e("www1", "抓拍返回后压缩后 时间：" + time1);
                                    Log.e("www1", "图片显示时间：" + 400);
//                                    doShowDialog();
                                    soundPool.play(1, 1, 1, 0, 0, 1);
                                    imgview.setImageBitmap(imagBitmap);
                                    imgview.setVisibility(View.VISIBLE);
                                    timerImgView = new Timer();
                                    taskImgView = new TimerTask() {
                                        @Override
                                        public void run() {
                                            // 需要做的事:发送消息  
                                            Message message = new Message();
                                            message.what = 2;

                                            handler.sendMessage(message);
                                            //异步上传图片
                                            UploadImage(DatetimeUtil.Bitmap2StrByBase64(Newbm), whik, finalMUserId);

                                            //清除bitmap
                                            if (null != Newbm && !Newbm.isRecycled()) {
                                                Newbm.recycle();
                                            }
                                            if (null != rectBitmap && !rectBitmap.isRecycled()) {
                                                rectBitmap.recycle();
                                            }
                                            if (null != bitmap && !bitmap.isRecycled()) {
                                                bitmap.recycle();
                                            }

                                        }
                                    };
                                    timerImgView.schedule(taskImgView, 800);// 1s后执行task,经过1s再次执行

                                }
                            });

                        }
                    });
                }
            });

            main_gallery.setVisibility(View.GONE);
            main_lin.setVisibility(View.GONE);
            //快照动画显示
            try {
                GifDrawable gifDrawable = new GifDrawable(getResources(), R.drawable.camera_picture_one);
                imgview.setImageDrawable(gifDrawable);
                imgview.setVisibility(View.VISIBLE);
            } catch (Exception e) {
                e.printStackTrace();
            }
           /* mCamera.takePicture(null, null, new Camera.PictureCallback() {
                @Override
                public void onPictureTaken(byte[] bytes, Camera camera) {
                    Date curDate = new Date(System.currentTimeMillis());
                    long time = curDate.getTime() - startTime;
                    Log.e("www1", "抓拍返回时间：" + time);

                    //进度条
                    doShowDialog();
                    bitmap = BitmapFactory.decodeByteArray
                            (bytes, 0, bytes.length);//图片
                    Matrix matrix = new Matrix();
                    matrix.setRotate(90);
                    Bitmap Newbm = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);

//                    imgview.setImageBitmap(zoomImg(Newbm, 720, 700));

//                    Bitmap rotaBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
                    int x = Newbm.getWidth() / 2 - DST_RECT_WIDTH / 2;
                    int y = Newbm.getHeight() / 2 - DST_RECT_HEIGHT / 2;
                    Log.i(TAG, "rotaBitmap.getWidth() = " + Newbm.getWidth()
                            + " rotaBitmap.getHeight() = " + Newbm.getHeight() + "DST_RECT_HEIGHT" + DST_RECT_HEIGHT);
                    Bitmap rectBitmap = Bitmap.createBitmap(Newbm, x, y, DST_RECT_HEIGHT, DST_RECT_HEIGHT);
                    imgview.setImageBitmap(zoomImg(rectBitmap, 720, 700));
                    Date curDate1 = new Date(System.currentTimeMillis());
                    long time1 = curDate1.getTime() - startTime;
                    Log.e("www1", "抓拍返回后压缩时间：" + time1);
//                    UploadImage(DatetimeUtil.Bitmap2StrByBase64(Newbm), whik, realmHelper.queryDogById(whik).getUserId());

                    timerImgView = new Timer();
                    taskImgView = new TimerTask() {
                        @Override
                        public void run() {
                            // 需要做的事:发送消息  
                            Message message = new Message();
                            message.what = 2;
                            handler.sendMessage(message);
                        }
                    };
                    timerImgView.schedule(taskImgView, 400);// 1s后执行task,经过1s再次执行
                    if (null != Newbm && !Newbm.isRecycled()) {
                        Newbm.recycle();
                        Newbm = null;
                    }
                    if (null != rectBitmap && !rectBitmap.isRecycled()) {
                        rectBitmap.recycle();
                        rectBitmap = null;
                    }
                    if (null != bitmap && !bitmap.isRecycled()) {
                        bitmap.recycle();
                        bitmap = null;
                    }
                }
            });*/
        }
    }

    /**
     * 生成拍照后图片的中间矩形的宽度和高度
     *
     * @param w 屏幕上的矩形宽度，单位px
     * @param h 屏幕上的矩形高度，单位px
     * @return
     */
    private Point createCenterPictureRect(int w, int h) {

        int wScreen = DisplayUtil.getScreenMetrics(this).x;
        int hScreen = DisplayUtil.getScreenMetrics(this).y;
        int wSavePicture = doGetPrictureSize().y; //因为图片旋转了，所以此处宽高换位
        int hSavePicture = doGetPrictureSize().x; //因为图片旋转了，所以此处宽高换位
        float wRate = (float) (wSavePicture) / (float) (wScreen);
        float hRate = (float) (hSavePicture) / (float) (hScreen);
        float rate = (wRate <= hRate) ? wRate : hRate;//也可以按照最小比率计算

        int wRectPicture = (int) (w * wRate);
        int hRectPicture = (int) (h * hRate);
        return new Point(wRectPicture, hRectPicture);

    }

    public Point doGetPrictureSize() {
        Camera.Size s = mCamera.getParameters().getPictureSize();
        return new Point(s.width, s.height);
    }

    public Bitmap zoomImg(Bitmap bm, int newWidth, int newHeight) {
        // 获得图片的宽高   
        int width = bm.getWidth();
        int height = bm.getHeight();
        // 计算缩放比例   
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 取得想要缩放的matrix参数   
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 得到新的图片   www.2cto.com
        Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
        return newbm;
    }

    boolean am = true;
    boolean pm = true;
    boolean night = true;
    boolean Fig;
    boolean DataFig;
    String Bigen;
    String End, mBigenAbsenteeism;
    Timer timer = new Timer(true);
    TimerTask task = new TimerTask() {

        @Override
        public void run() {
            handler.sendEmptyMessage(1);
        }
    };

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    String sReStartFlag = mSharePreferenceUtil.getRestartFlag();
                    if (TextUtils.isEmpty(sReStartFlag)) {
                        mSharePreferenceUtil.setIndexBigen(0);
                        mSharePreferenceUtil.setIndexEnd(0);
                    } else {

                    }
                    if (DatetimeUtil.TimeCompare(getSysDate("HH:mm"), "00:00", "11:59") && am) {

                        am = false;
                        pm = true;
                        night = true;

                        Log.d("TAG", "早上");
                        String strAm = getSysDate("yyyy-MM-dd") + "am";//am


                        if (sReStartFlag.equals(strAm)) {//说明当天am 已经加载过了,重启进入
                            isReStart = true;
                            Log.d("HHH", "说明当天am 已经加载过了,重启进入" + strAm);
                        } else {//第一次
                            GetClass();
                            mSharePreferenceUtil.setRestartFlag(strAm);
                            Log.d("HHH", "说明当天am ,第一次进入" + strAm);
                            indexBigen = 0;
                            indexEnd = 0;
                            mSharePreferenceUtil.setIndexBigen(indexBigen);
                            mSharePreferenceUtil.setIndexEnd(indexEnd);
                        }
                    }
                    if (DatetimeUtil.TimeCompare(getSysDate("HH:mm"), "12:00", "17:59") && pm) {

                        am = true;
                        night = true;
                        pm = false;
                        Log.d("TAG", "下午");

                        String strPm = getSysDate("yyyy-MM-dd") + "pm";//pm


                        if (sReStartFlag.equals(strPm)) {//说明当天am 已经加载过了,重启进入
                            isReStart = true;
                            Log.d("HHH", "说明当天pm 已经加载过了,重启进入" + strPm);
                        } else {//第一次
                            GetClass();
                            mSharePreferenceUtil.setRestartFlag(strPm);
                            Log.d("HHH", "说明当天pm,第一次进入" + strPm);
                            indexBigen = 0;
                            indexEnd = 0;
                            mSharePreferenceUtil.setIndexBigen(indexBigen);
                            mSharePreferenceUtil.setIndexEnd(indexEnd);
                        }
                    }
                    if (DatetimeUtil.TimeCompare(getSysDate("HH:mm"), "18:00", "23:59") && night) {

                        am = true;
                        night = false;
                        pm = true;
                        Log.d("TAG", "晚上");

                        String strNight = getSysDate("yyyy-MM-dd") + "night";//night

                        if (sReStartFlag.equals(strNight)) {//说明当天am 已经加载过了,重启进入
                            isReStart = true;
                            Log.d("HHH", "strNight 已经加载过了,重启进入" + strNight);
                        } else {//第一次
                            GetClass();
                            mSharePreferenceUtil.setRestartFlag(strNight);
                            Log.d("HHH", "strNight 已经加载过了,第一次进入" + strNight);
                            indexBigen = 0;
                            indexEnd = 0;
                            mSharePreferenceUtil.setIndexBigen(indexBigen);
                            mSharePreferenceUtil.setIndexEnd(indexEnd);
                        }

                    }


                    indexBigen = mSharePreferenceUtil.getIndexBigen();
                    indexEnd = mSharePreferenceUtil.getIndexEnd();
                    subscript = mSharePreferenceUtil.getSubscript();
                    Fig = mSharePreferenceUtil.getFig();
                    DataFig = mSharePreferenceUtil.getDataFig();

                    BigenCard = MyApp.getsInstance().getBigenCard();
                    EndCard = MyApp.getsInstance().getEndCard();
                    MeetingId = MyApp.getsInstance().getMeetingId();

                    if (isReStart) {
                        doReadCardSetting();
//                        mMsgQueue.clear();
//                        loadMusic();
                        Log.d("wwww", "重启机制--");
                        isReStart = false;
                        List<String> MeetingIdT = (List<String>) MyFileUtils.readFile2Object1(MyFileUtils.MeetingId, new TypeToken<List<String>>() {
                        }.getType());

                        if (null != MeetingIdT) {
                            MeetingId.clear();
                            MeetingId.addAll(MeetingIdT);
                        }

                        List<String> BigenCardT = (List<String>) MyFileUtils.readFile2Object1(MyFileUtils.BigenCard, new TypeToken<List<String>>() {
                        }.getType());
                        if (null == BigenCard) {
                            BigenCard = new ArrayList<String>();
                        }
                        Log.d("ffff1", "BigenCardT-size-" + BigenCardT.size() + "BigenCard-size-" + BigenCard.size());
                        if (null != BigenCardT) {
                            if (BigenCard.size() > 0) {
                                BigenCard.clear();
                            }
                            BigenCard.addAll(BigenCardT);
                            Log.d("ffff2", "addadd==" + BigenCard.size());
                        }

                        List<String> EndCardT = (List<String>) MyFileUtils.readFile2Object1(MyFileUtils.EndCard, new TypeToken<List<String>>() {
                        }.getType());

                        if (null != EndCardT) {
                            EndCard.clear();
                            EndCard.addAll(EndCardT);
                        }
                        // 人员信息
                   /*     List<PersonnelResutl> mlist = (List<PersonnelResutl>) MyFileUtils.readFile2Object1(MyFileUtils.mListBean, new TypeToken<List<PersonnelResutl>>() {
                        }.getType());

                        if (mlist != null && mlist.size() > 0) {
                                if (list != null && list.size() > 0) {
                                    list.clear();
                                    Log.e(TAG, "重启-mlist-fixid-mListBean.clear()");
                                }
                                list.addAll(mlist);
                                Log.e(TAG, "重启-mlist-fixid mListBean.addAll(mlist)" + list.toString());
                                for (int i = 0; i < list.size(); i++) {
                                    Log.d("www", list.get(i).toString());
                                }

                                sortClass sort = new sortClass();
                                Collections.sort(list, sort);*/

                             /*   attendanceAdapter = new AttendanceAdapter(MainActivity.this);
                                listView.setAdapter(attendanceAdapter);
                                attendanceAdapter.clear();
                                attendanceAdapter.setDate(list);*/
                        list = realmHelper.queryDobByAge(MeetingId.get(mSharePreferenceUtil.getIndexBigen()));
                        initAttAdapter();

                        RealmResults<MeetingResutl> dog = realmHelper.querMeetingResutllById(MeetingId.get(indexBigen));
                        if (null != dog && dog.size() > 0) {
                            meetingResutl = realmHelper.querMeetingResutll(MeetingId.get(indexBigen));
                        }
                        if (null != meetingResutl) {
                            practical.setText(mSharePreferenceUtil.getRealized() + "/" + meetingResutl.getExtField05() + "/" + list.size() + "");
                        }


                        //图片信息
                        List<String> mli = (List<String>) MyFileUtils.readFile2Object1(MyFileUtils.mListAttachUrl, new TypeToken<List<String>>() {
                        }.getType());
                        if (mli != null && mli.size() > 0) {
                            Log.e("TAG", "重启-mli-ArrURl-" + mli.get(0) + "");
                            if (li != null && li.size() > 0) {
                                li.clear();
                            }
                            li.addAll(mli);
//                                gallery_adapter.setList(li);
                            initGallery_adapter();
                            setCircle();
                        }
                    }
                    Log.d("ffff", "BigenCard.size()--" + BigenCard.size());

                    if (BigenCard.size() != 0 && indexBigen < BigenCard.size() && indexEnd < EndCard.size()) {//
                        if (indexBigen >= BigenCard.size() || indexEnd >= EndCard.size()) {
                            indexBigen = BigenCard.size() - 1;
                            indexEnd = EndCard.size() - 1;
                            return;
                        }

                        RealmResults<MeetingResutl> dog = realmHelper.querMeetingResutllById(MeetingId.get(indexBigen));
                        if (null != dog && dog.size() > 0) {
                            meetingResutl = realmHelper.querMeetingResutll(MeetingId.get(indexBigen));
                        } else {
                            Log.e("TAG", "dog==null");
                            return;
                        }
//                        MeetingResutl meetingResutl = realmHelper.querMeetingResutll(MeetingId.get(indexBigen));
                        Bigen = DatetimeUtil.getDateTimeFromMillisecond(
                                DatetimeUtil.TimeStrToSecond(BigenCard.get(indexBigen)) - 1000 * 60 * (meetingResutl.getInBefore()));
                        if (meetingResutl.getNeedCheckout() == 1) {
                            End = DatetimeUtil.getDateTimeFromMillisecond(
                                    DatetimeUtil.TimeStrToSecond(EndCard.get(indexEnd)) + 1000 * 60 * (meetingResutl.getOutLate()));
                            strEnd = DatetimeUtil.getDateTimeFromMillisecond(
                                    DatetimeUtil.TimeStrToSecond(EndCard.get(indexEnd)) + 1000 * 60 * meetingResutl.getOutLate() + 1000 * 60 * 1);
                        } else {
                            End = DatetimeUtil.getDateTimeFromMillisecond(
                                    DatetimeUtil.TimeStrToSecond(EndCard.get(indexEnd)));
                            strEnd = DatetimeUtil.getDateTimeFromMillisecond(
                                    DatetimeUtil.TimeStrToSecond(EndCard.get(indexEnd)) + 1000 * 60 * 1);
                        }
                        mBigenAbsenteeism = DatetimeUtil.getDateTimeFromMillisecond(
                                DatetimeUtil.TimeStrToSecond(BigenCard.get(indexBigen)) + 1000 * 60 * (meetingResutl.getAbsenteeism()));
                     /*   End = DatetimeUtil.getDateTimeFromMillisecond(
                                DatetimeUtil.TimeStrToSecond(EndCard.get(indexEnd)) + 1000 * 60 * (meetingResutl.getOutLate()));
//                        Bigen = DatetimeUtil.getDateTimeFromMillisecond(
//                                DatetimeUtil.TimeStrToSecond(BigenCard.get(indexBigen))  );
//                        End = DatetimeUtil.getDateTimeFromMillisecond(
//                                DatetimeUtil.TimeStrToSecond(EndCard.get(indexEnd)) );
                        strEnd = DatetimeUtil.getDateTimeFromMillisecond(
                                DatetimeUtil.TimeStrToSecond(EndCard.get(indexEnd)) + 1000 * 60 * meetingResutl.getOutLate() + 1000 * 60 * 1);
*/

                        Log.d("TAG", "开始时间：" + Bigen);
                        Log.d("TAG", "结束时间：" + End);
                        Log.d("TAG", "延迟缺勤时间：" + mBigenAbsenteeism);
                        Log.d("TAG", "getInBefore：" + meetingResutl.getInBefore());
                        Log.d("TAG", "getOutLate：" + meetingResutl.getOutLate());
                        //重启机制

                        //
                        if (DatetimeUtil.TimeCompare(getSysDate("HH:mm"), DatetimeUtil.gethour(Bigen), DatetimeUtil.gethour(End)) && (!subscript)) {
                            Log.d("wwwww", "在范围加载数据---indexBigen：" + indexBigen);

                            mSharePreferenceUtil.setSubscript(true);
                            mSharePreferenceUtil.setIndexBigen(indexBigen);
                            Log.d("TAG", "在范围：");
                            li.clear();


                            for (int i = 0; i < realmHelper.QueryImag(MeetingId.get(mSharePreferenceUtil.getIndexBigen())).size(); i++) {
                                Attachment attachment = ((Attachment) realmHelper.QueryImag(MeetingId.get(mSharePreferenceUtil.getIndexBigen())).get(i));
                                li.add(attachment.getAttachUrl());

                            }
                            Log.d("TAG", "li:" + realmHelper.QueryImag(MeetingId.get(mSharePreferenceUtil.getIndexBigen())).size());
                            Log.d("TAG", "li:" + li.size());
                            if (li.size() != 0) {
//                                gallery_adapter.setList(li);
                                initGallery_adapter();
                                setCircle();
                            }

                            list = realmHelper.queryDobByAge(MeetingId.get(mSharePreferenceUtil.getIndexBigen()));
                            Log.d("wwwww", "在范围加载数据---：list1" + MeetingId.get(mSharePreferenceUtil.getIndexBigen()));
                            Log.d("wwwww", "在范围加载数据---：list2" + mSharePreferenceUtil.getIndexBigen());
                            Log.d("wwwww", "在范围加载数据---：list3" + list.size());
                            practical.setText(mSharePreferenceUtil.getRealized() + "/" + meetingResutl.getExtField05() + "/" + list.size());


                            listView.setVisibility(View.VISIBLE);
//                            attendanceAdapter = new AttendanceAdapter(MainActivity.this);
//                            listView.setAdapter(attendanceAdapter);
////                            attendanceAdapter.clear();
//                            attendanceAdapter.setDate(list);
                            initAttAdapter();

                            PersonnelResutl resutl = realmHelper.FandPersonnelResultByMedtingId(MeetingId.get(mSharePreferenceUtil.getIndexBigen()), 0);
                            if (null != resutl) {
                                realmHelper.UpdateFindllTye(MeetingId.get(mSharePreferenceUtil.getIndexBigen()), 0);
                            }

                            mSharePreferenceUtil.setFig(false);

                            ThreadUtil.getInstance().submit(new Runnable() {
                                @Override
                                public void run() {
                                    MyFileUtils.deleteFile(MyFileUtils.mListBean);
                                    MyFileUtils.deleteFile(MyFileUtils.mListAttachUrl);
                                    list.get(0).setmCurrenTime(Bigen);
                                    boolean isSave = MyFileUtils.saveObject2File(list, MyFileUtils.mListBean);
                                    Log.d(TAG, "默认保存 缓存数据-PersonnelResutl-" + isSave);
                                    boolean isSaveUrl = MyFileUtils.saveObject2File(li, MyFileUtils.mListAttachUrl);
                                    Log.d(TAG, "默认保存课程图片URL保存--" + isSaveUrl);
                                }
                            });
                        }
                        Log.d("TAG", "fig:" + Fig);
                        if (getSysDate("yyyy-MM-dd HH:mm:ss").equals(mBigenAbsenteeism)) {
                            Log.d("TAG", "提前时间上传---" + mBigenAbsenteeism);
                            UploadCheck(DataFig, true);


                        }
                        if (getSysDate("yyyy-MM-dd HH:mm:ss").equals(End) && (!Fig)) {
                            if ((MeetingId.size() - 1) == indexBigen) {
                                List<MeetingResutl> mlist = new ArrayList<>();
                                setupViews(R.layout.layout_depar, R.layout.layout_department, R.id.layout_more, R.id.layout_more1, R.id.tiee, mlist);
                                initReGllery();
                            }
                            UploadCheck(DataFig, false);
                            mSharePreferenceUtil.setSubscript(false);
                            practical.setText(0 + "/" + 0 + "/" + 0);
                            Log.d("wwwwww", "BigenCard-size==" + BigenCard.size());
                            if (BigenCard.size() - 1 == indexBigen) {
                                List<MeetingResutl> mlist = new ArrayList<>();
                                setupViews(R.layout.layout_depar, R.layout.layout_department, R.id.layout_more, R.id.layout_more1, R.id.tiee, mlist);
                            }
                            realized = 0;
                            mSharePreferenceUtil.setRealized(0);
                            indexEnd++;
                            indexBigen++;
                            mSharePreferenceUtil.setIndexEnd(indexEnd);
                            mSharePreferenceUtil.setIndexBigen(indexBigen);
                            listView.setVisibility(View.GONE);
                            list.clear();
                            initAttAdapter();
                            Log.e("TAG", "清除不同时区的所有缓存 数据...");
                            ThreadUtil.getInstance().submit(new Runnable() {
                                @Override
                                public void run() {
                                    MyFileUtils.deleteFile(MyFileUtils.mListBean);//
                                    MyFileUtils.deleteFile(MyFileUtils.mListAttachUrl);//
                                    mSharePreferenceUtil.setRestartFlag("");
                                    mSharePreferenceUtil.setIndexEnd(0);
                                    mSharePreferenceUtil.setIndexBigen(0);
                                }
                            });

                        }

                        if (mSharePreferenceUtil.getIsManualUpload()) {//手动上传标记
                            mSharePreferenceUtil.setIsManualUpload(false);
                            UploadCheck(DataFig, false);

                            signDialog = SignDialog.show(TestMainActivity.this, "上传成功！", "");


                            timerImgView = new Timer();
                            taskImgView = new TimerTask() {
                                @Override
                                public void run() {
                                    Message message = new Message();
                                    message.what = 5;
                                    handler.sendMessage(message);
                                }
                            };
                            timerImgView.schedule(taskImgView, 800);

                            //删除 会议对应人员信息
                            realmHelper.deletePersonByMeetingId(MeetingId.get(mSharePreferenceUtil.getIndexBigen()));

                            mSharePreferenceUtil.setSubscript(false);
                            practical.setText(0 + "/" + 0 + "/" + 0);
                            realized = 0;
                            mSharePreferenceUtil.setRealized(0);
                            indexEnd++;
                            indexBigen++;
                            mSharePreferenceUtil.setIndexEnd(indexEnd);
                            mSharePreferenceUtil.setIndexBigen(indexBigen);
                            listView.setVisibility(View.GONE);
                            if (attendanceAdapter != null) {
                                list.clear();
                                attendanceAdapter.notifyDataSetChanged();
                            }


                            Log.e("TAG", "清除不同时区的所有缓存 数据...");
                            ThreadUtil.getInstance().submit(new Runnable() {
                                @Override
                                public void run() {
                                    MyFileUtils.deleteFile(MyFileUtils.mListBean);//
                                    MyFileUtils.deleteFile(MyFileUtils.mListAttachUrl);//
                                    mSharePreferenceUtil.setRestartFlag("");
                                    mSharePreferenceUtil.setIndexEnd(0);
                                    mSharePreferenceUtil.setIndexBigen(0);
                                }
                            });

                        }

                        Log.d("TAG", "时间：" + DatetimeUtil.gethour(DatetimeUtil.getDateTimeFromMillisecond(
                                DatetimeUtil.TimeStrToSecond(End) + 1000 * 60 * 3)));

//                        if (DatetimeUtil.TimeCompare(DatetimeUtil.getSysDate("HH:mm"), DatetimeUtil.gethour(End), DatetimeUtil.gethour(DatetimeUtil.getDateTimeFromMillisecond(
//                                DatetimeUtil.TimeStrToSecond(End) + 1000 * 60 * 3))) && (!Fig)) {
//                            UploadCheck(DataFig);
//                            mSharePreferenceUtil.setSubscript(false);
//                            practical.setText(0 + "/" + 0);
//                            mSharePreferenceUtil.setRealized(0);
////                        mSharePreferenceUtil.setIndexEnd(indexEnd);
//                            Log.d("TAG", "3分钟上传");
//                        }

                    } else {
                       /*  Log.d("TAG", "不在时间--strEnd" + strEnd);
                        //不当前 时区内 且 在 当前课程结束后 2分钟后 清除缓存 ，上传遗留的记录
                        if (TextUtils.isEmpty(strEnd)) {
                            return;
                        }
                       if (DatetimeUtil.TimeCompareEnd(getSysDate("HH:mm"), DatetimeUtil.gethour(strEnd))) {
                            ThreadUtil.getInstance().submit(new Runnable() {
                                @Override
                                public void run() {
                                    Log.d("TAG", "2当前课程结束" + strEnd + " + 2分钟后 清除缓存 ，查上传遗留的记录 有需要上传的数据...");
                                    MyFileUtils.deleteFile(MyFileUtils.mListBean);
                                    MyFileUtils.deleteFile(MyFileUtils.mListAttachUrl);
                                    mSharePreferenceUtil.setRestartFlag("");
                                    mSharePreferenceUtil.setIndexEnd(0);
                                    mSharePreferenceUtil.setIndexBigen(0);
                                    strEnd = "";
                                }
                            });

                        }*/
                    }


                    break;

                case 2:
                    Log.d("TAG", " 接受 Message message===2");
                    isLoading = false;
                    Date curDate = new Date(System.currentTimeMillis());
                    long time = curDate.getTime() - startTime;
                    Log.e("www1", "接受 延迟后 400 完成整个拍照显示图片时间：" + time);
                    imgview.setImageBitmap(null);
                    main_gallery.setVisibility(View.VISIBLE);
                    main_lin.setVisibility(View.VISIBLE);
                    imgview.setVisibility(View.GONE);

                    if (MyDialog != null) {
                        MyDialog.dismiss();
                    }

                    if (timerImgView != null) {
                        taskImgView.cancel();
                    }
                    if (timer != null) {
                        task.cancel();
                    }
                    timer = new Timer();
                    task = new TimerTask() {
                        @Override
                        public void run() {
                            // 需要做的事:发送消息  
                            Message message = new Message();
                            message.what = 1;
                            handler.sendMessage(message);
                        }
                    };
                    timer.schedule(task, 1000, 1000);// 1s后执行task,经过1s再次执行

                    break;
                case 3:
                    SetData(tiem);
                    break;
                case 4:

                    break;
                case 5:
                    Log.d("TAG", "手动上传Success--");
                    if (signDialog != null && signDialog.isShowing()) {
                        signDialog.dismiss();
                        signDialog = null;
                    }
                    if (timerImgView != null) {
                        taskImgView.cancel();
                    }

                    break;
            }
        }
    };
    String strEnd;

    private void Date(String name) {
        realized = mSharePreferenceUtil.getRealized();
        MeetingCheck meetingCheck = new MeetingCheck();
        indexBigen = mSharePreferenceUtil.getIndexBigen();


//        list = realmHelper.queryDobByAge(MeetingId.get(mSharePreferenceUtil.getIndexBigen()));
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getWlkh() != null) {
                if (list.get(i).getWlkh().equals(name)) {
                    Log.e("www", list.get(i).toString());
                    list.get(i).setTime(getSysDate("HH:mm:ss"));
                    realmHelper.UpdateDog(name, MeetingId.get(mSharePreferenceUtil.getIndexBigen()), getSysDate("HH:mm:ss"));
//                    meetingCheck.setClassId(list.get(i).getClassId());
                    meetingCheck.setInResult("4");
                    meetingCheck.setTermCode(mSharePreferenceUtil.getClassId());
                    meetingCheck.setLg("0");
                    meetingCheck.setMeetingId(list.get(i).getMeetingId());
                    meetingCheck.setUserId(list.get(i).getUserId());
                    meetingCheck.setTime(getSysDate("yyyy-MM-dd HH:mm:ss"));
                    Log.d("TAG", "Time:" + meetingCheck.getTime());
                    Log.d("TAG", "getInResult:" + meetingCheck.getInResult());
                    if (meetingCheck.getInResult().equals("1")) {
                        meetingCheck.setAttendResult("1");
                    } else if (meetingCheck.getInResult().equals("2")) {
                        meetingCheck.setAttendResult("2");

                    } else if (meetingCheck.getInResult().equals("4")) {
                        meetingCheck.setAttendResult("4");
                    }
                    meetingCheck.setWlkh(name);
                    if (list.get(i).getType() == 0) {
                        realized++;
                        mSharePreferenceUtil.setRealized(realized);
                    }
                    list.get(i).setType(1);
                    initAttAdapter();
                    Log.d("TAG", "type:" + list.get(i).getType());
                    realmHelper.UpdateDogTye(name, MeetingId.get(mSharePreferenceUtil.getIndexBigen()), 1);
                    meetingCheck.setOutResult("0");
                    realmHelper.addDog(meetingCheck);
                    break;

                }
            }
        }
        sortClass sort = new sortClass();
        Collections.sort(list, sort);
        initAttAdapter();
        //  list = realmHelper.queryDobByAge(MeetingId.get(mSharePreferenceUtil.getIndexBigen()));
        practical.setText(mSharePreferenceUtil.getRealized() + "/" + meetingResutl.getExtField05() + "/" + list.size());


        ThreadUtil.getInstance().submit(new Runnable() {
            @Override
            public void run() {
                MyFileUtils.deleteFile(MyFileUtils.mListBean);
                boolean isSave = MyFileUtils.saveObject2File(list, MyFileUtils.mListBean);
                Log.d("TAG", "刷卡保存--" + isSave);
            }
        });
    }

    private void UploadCheck(boolean dataFig, final boolean isAas) {
        Log.d("TAG", "fig1:" + Fig);
        list1.clear();
        BigenCard = MyApp.getsInstance().getBigenCard();
        indexEnd = mSharePreferenceUtil.getIndexEnd();
        MeetingId = MyApp.getsInstance().getMeetingId();
        MeetingResutl meetingResutl = realmHelper.querMeetingResutll(MeetingId.get(indexBigen));
        final List<PersonnelResutl> list = realmHelper.queryDobByAge(MeetingId.get(indexEnd));
        Log.d("TAG", "list:" + list.size());
        if (list.size() != 0) {//&& (!dataFig)
            for (int i = 0; i < list.size(); i++) {
                Log.d("TAG", "list:" + list.get(i).getWlkh());
              /*  if (realmHelper.QueryTraineeId(list.get(i).getUserId(), list.get(i).getMeetingId()).size() == 0) {
                    MeetingCheck meetingCheck = new MeetingCheck();
                    meetingCheck.setInResult("4");
                    meetingCheck.setMeetingId(list.get(i).getMeetingId());
                    meetingCheck.setTermCode(mSharePreferenceUtil.getClassId());
                    meetingCheck.setLg("-1");
                    meetingCheck.setTime(null);
                    meetingCheck.setWlkh(list.get(i).getWlkh());
                    meetingCheck.setOutResult("0");
                    meetingCheck.setAttendResult("4");
                    meetingCheck.setUserId(list.get(i).getUserId());
                    Log.d("TAG", "UserId:" + list.get(i).getUserId());
                    realmHelper.addDog(meetingCheck);
                }*/

                {
                    if (realmHelper.QueryTraineeId(list.get(i).getUserId(), list.get(i).getMeetingId()).size() >= 1) {
                        if (DatetimeUtil.Getminutes(realmHelper.queryDogByIdOne(list.get(i).getWlkh()).getTime(), BigenCard.get(indexBigen)) <= (meetingResutl.getBeLate() + meetingResutl.getAbsenteeism())) {
                            realmHelper.updateInResultOne(list.get(i).getWlkh(), "1");
                            realmHelper.updateAttendResult(list.get(i).getWlkh(), "1");
                        } else {
                            realmHelper.updateInResultOne(list.get(i).getWlkh(), "2");
                            realmHelper.updateAttendResult(list.get(i).getWlkh(), "2");

                        }
                    }
//
                    realmHelper.UpdateLgOne(list.get(i).getWlkh(), "0");  //改状态 签到 "0"
                    if (realmHelper.queryDogByIdOne(list.get(i).getWlkh()) != null) {
                        if (realmHelper.queryDogByIdOne(list.get(i).getWlkh()).getTime() == null) {
                            realmHelper.UpdateLgOne(list.get(i).getWlkh(), "-1");
                            realmHelper.updateInResultOne(list.get(i).getWlkh(), "4");
                            realmHelper.updateAttendResultOne(list.get(i).getWlkh(), list.get(i).getUserId(), "4");
                        }

                    }
                    list1.add(realmHelper.QueryTraineeIdOne(list.get(i).getUserId(), list.get(i).getMeetingId(), 1));
                    Log.d("TAG", "没开启签退");
                }

            }


        }


        mSharePreferenceUtil.setDataFig(true);
        String json = JSON.toJSONString(list1);
        Log.d("TAG", "json:" + json);
        Log.d("TAG", "list1:" + list1.size());

        Subscriber subscr = new AbsAPICallback<Resutl>(this) {
            @Override
            public void onCompleted() {
                Log.d("TAG", "上传完成onCompleted");
            }


            @Override
            public void onNext(Resutl resul) {
                Log.d("TAG", "resul:" + resul.getMessage());
                Log.d("TAG", "isCode:" + resul.isCode());

                if (resul.isCode()) {
                    if (isAas) {
                        Log.d("TAG", "提前时间上传成功");

                    } else {
                        Log.d("TAG", "自动结束上传成功");
                        BigenCard.clear();
                        EndCard.clear();
                        MyApp.getsInstance().setBigenCard(BigenCard);
                        MyApp.getsInstance().setEndCard(EndCard);
                        MyFileUtils.deleteFile(MyFileUtils.mListBean);
                        MyFileUtils.deleteFile(MyFileUtils.mListAttachUrl);
                        mSharePreferenceUtil.setRestartFlag("");
                        mSharePreferenceUtil.setIndexEnd(0);
                        mSharePreferenceUtil.setIndexBigen(0);
                        strEnd = "";

                        realmHelper.deleteDogMeeting(list.get(indexBigen).getMeetingId());
                        realmHelper.deleteDog(list.get(indexBigen).getMeetingId());
                        list1.clear();
                        mSharePreferenceUtil.setRealized(0);
                        mSharePreferenceUtil.setFig(true);
                        mSharePreferenceUtil.setDataFig(false);
                        list.clear();
                        initAttAdapter();
                        listView.setVisibility(View.GONE);
                        practical.setText("0/0/0");
                    }
                }

            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                Log.i("TAG", "e：" + e.getMessage());
                Log.d("TAG", "上传失败");
            }
        };
        Api.getInstance().UploadCheck(subscr, json);


    }

    private <VT extends View> VT getView(@IdRes int id) {
        return (VT) findViewById(id);
    }


    private class SufaceListener implements SurfaceHolder.Callback {
        private boolean isPreview;

        @Override
        public void surfaceCreated(SurfaceHolder surfaceHolder) {
            try {
                WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
                Display display = wm.getDefaultDisplay();
                //int num = mCamera.getNumberOfCameras();
                mCamera = Camera.open(0);
                Camera.Parameters parameters = mCamera.getParameters();
                List<Camera.Size> vSizeList = parameters.getSupportedPictureSizes();

                for (int num = 0; num < vSizeList.size(); num++) {
                    Camera.Size vSize = vSizeList.get(num);
                }

                if (getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
                    //如果是竖屏
                    mCamera.setDisplayOrientation(90);
                } else {
                    mCamera.setDisplayOrientation(180);
                }
                parameters.setPictureFormat(PixelFormat.JPEG);
                mCamera.setParameters(parameters);
                mCamera.setPreviewDisplay(mSurfaceHolder);
                mCamera.startPreview();
                isPreview = true;
                Log.d("TAG", "执行");
            } catch (Exception e) {
                Toast.makeText(TestMainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                Log.d("TAG", "e:" + e.getMessage());
            }
        }

        @Override
        public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
            if (mSurfaceHolder == null) {
                // preview surface does not exist
                return;
            }

            // stop preview before making changes
            try {
                if (mCamera != null) {
                    mCamera.stopPreview();

                }

            } catch (Exception e) {
                // ignore: tried to stop a non-existent preview
            }

            try {
                mCamera.setPreviewDisplay(mSurfaceHolder);
                mCamera.startPreview();

            } catch (Exception e) {

            }
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
            if (mCamera != null) {
                if (isPreview) mCamera.stopPreview();
                mCamera.release();
                mCamera = null;
            }
        }
    }

    @Override
    public void onDestroy() {
        Log.w("TAG", "onDestroy---");
        if (signDialog != null) {
            signDialog.dismiss();
            signDialog = null;
        }
        //销毁activity之前先关闭定时器
        if (handler != null) {
            if (timeadv != null) {
                handler.removeCallbacks(timeadv);
            }
        }
        RxBus.get().unregister(this);
        if (MyDialog != null) {
            MyDialog.dismiss();
            MyDialog = null;
        }
//        clearShounPool();//放所有使用的本地资源
        cancellTask();//释放Task
        clearList();//释放集合
        removeHandler();//停止计时器
        super.onDestroy();
    }

    private void cancellTask() {
      /*  if (addTask != null && !addTask.isCancelled()) {
            addTask.cancel();
            addTask = null;
        }*/
    }

    private void removeHandler() {

//        handler.removeCallbacks(runnableNotice);
//        handler.removeCallbacks(runnableReStart);
//        handler.removeCallbacks(runnableGradeClear);
//        handler.removeCallbacks(dingTimeRunable);
    }

    private void clearList() {
     /*   if (mVideoCardList != null) {
            mVideoCardList.clear();
            mVideoCardList = null;
        }*/
    }

    private void clearShounPool() {
        if (soundPool != null) {//放所有使用的本地资源
            soundPool.release();
            soundPool = null;
        }
        if (soundPool1 != null) {
            soundPool1.release();
            soundPool1 = null;
        }
        if (soundPool2 != null) {
            soundPool2.release();
            soundPool2 = null;
        }
    }

    private void loadMusic() {

                soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 5);
                soundPool1 = new SoundPool(10, AudioManager.STREAM_MUSIC, 5);
                soundPool2 = new SoundPool(10, AudioManager.STREAM_MUSIC, 5);
                failure = soundPool1.load(myActivity, R.raw.failure, 0);
                sourceid = soundPool.load(myActivity, R.raw.media, 0);
                credit = soundPool2.load(myActivity, R.raw.q_ni_already_dao, 0);
                soundPool
                        .setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {

                            public void onLoadComplete(SoundPool soundPool,
                                                       int sampleId, int status) {
                                isSoundReady = true;

                            }
                        });
                soundPool1
                        .setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {

                            public void onLoadComplete(SoundPool soundPool,
                                                       int sampleId, int status) {
                                isSoundReady = true;

                            }
                        });
                soundPool2
                        .setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {

                            public void onLoadComplete(SoundPool soundPool,
                                                       int sampleId, int status) {
                                isSoundReady = true;

                            }
                        });



    }


    private void SetData(TextView tiem) {
        date.setText(getSysDate("yyyy年MM月dd日"));
        week.setText("星期" + DatetimeUtil.getWhere());
        tiem.setText(getSysDate("HH:mm:ss"));
    }

    public class MyThread implements Runnable {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            while (true) {
                try {
                    Thread.sleep(1000);//线程暂停1秒，单位毫秒
                    Message message = new Message();
                    message.what = 3;
                    handler.sendMessage(message);//发送消息
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.set:
                SetDiagFragment setDiagFragment = new SetDiagFragment();
                setDiagFragment.show(getFragmentManager(), SetDiagFragment.class.getName());

                break;
            case R.id.imgview1:
                Intent intent = new Intent(Intent.ACTION_MAIN);
                //知道要跳转应用的包名、类名
                ComponentName componentName = new ComponentName("com.yc.class_attendance", "com.yc.class_attendance.ReMainActivity");
                intent.setComponent(componentName);
                startActivity(intent);
                doClearDataReStart();
                break;
        }
    }

    /**
     * 清除缓存
     */
    private void doClearDataReStart() {
        //
        mSharePreferenceUtil.setRestartFlag("");
        mSharePreferenceUtil.setRealized(0);
        mSharePreferenceUtil.setIndexEnd(0);
        mSharePreferenceUtil.setIndexBigen(0);
        mSharePreferenceUtil.setSubscript(false);
        mSharePreferenceUtil.setFig(false);
        mSharePreferenceUtil.setDataFig(false);
        mSharePreferenceUtil.setIsFlagTui(false);
        mSharePreferenceUtil.setIsManualUpload(false);
        System.exit(0);

    }


    private class DispQueueThread extends Thread {
        private Queue<ComBean> QueueList = new LinkedList<ComBean>();

        @Override
        public void run() {
            super.run();
            while (!isInterrupted()) {
                final ComBean ComData;
                while ((ComData = QueueList.poll()) != null) {
                    runOnUiThread(new Runnable() {
                        public void run() {

                            DispRecDataTest(ComData);
                        }
                    });
                    try {
                        Thread.sleep(100);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                }
            }
        }

        public synchronized void AddQueue(ComBean ComData) {
            QueueList.add(ComData);
        }
    }

    String cardId = "";// 当前 刷卡卡号临时变量
    private CountDownTimer mDownTimer;

    private void startDowntime() {
        initDownTime();
      /*  if (null == mDownTimer) {
            initDownTime();
        } else {
            mDownTimer.start();
        }*/
    }

    private final int TIME = 500 * 1;//每1秒更新界面 年月日 时分秒

    private void initDownTime() {
        mDownTimer = new CountDownTimer(TIME, 2500) {
            @Override
            public void onTick(long l) {

                Log.d("dowm==", "onTick--");
            }

            @Override
            public void onFinish() {
               /* if (null != myActivity) {
                    cardId = "";
                    Log.d("dowm==", "onFinish 1秒后 TIME isOne--cardId = 空");
                    mDownTimer.cancel();
                }*/
                cardId = "";
                Log.d("dowm==", "onFinish 1秒后 TIME isOne--cardId = 空");
                if(null!=mDownTimer){
                    mDownTimer.cancel();
                    mDownTimer = null;
                }

            }


        };
        mDownTimer.start();
    }
    Date lastDate = new Date(System.currentTimeMillis());
    String lastCard ="";
    private void DispRecDataTest(ComBean ComRecData) {
      /*  StringBuilder sMsg = new StringBuilder();
        sMsg.append(ComRecData.sRecTime);
        sMsg.append("[");
        sMsg.append(ComRecData.sComPort);
        sMsg.append("]");
        sMsg.append("[Hex] ");*/
//        if (!isValid()) {
//            setRecvData(ComRecData.bRec);
//            //解析 TLV 格式数据
//
//            setValidDataFlag(true);
//        }


        Log.d("res", MyFunc.ByteArrToHex(ComRecData.bRec));
        // 10/17直接获取ID
        String resData = MyFunc.ByteArrToHex(ComRecData.bRec).trim();
        Log.d("res", "resData.length=" + resData.length());
        if (resData.endsWith("6B BB") && resData.length() >= 38) {
            Log.d("res", "10/17直接获取ID");
            String re = resData.substring(resData.length() - 20, resData.length() - 9);
            System.out.println(re);
            String[] rr = re.split(" ");
            String[] dd = new String[4];
            StringBuilder sb = new StringBuilder();
            dd[0] = rr[3];
            dd[1] = rr[2];
            dd[2] = rr[1];
            dd[3] = rr[0];
            for (int i = 0; i < dd.length; i++) {
                System.out.println(dd[i]);
                sb.append(dd[i]);
            }
            String curCard= sb.toString();
            String factoryFixID= sb.toString();
            Log.d("res", "物理卡号：factoryFixID=" + curCard + "cardId=" + cardId);
            if (!TextUtils.isEmpty(curCard)) {

                Date curDate = new Date(System.currentTimeMillis());
                long time = curDate.getTime() - lastDate.getTime();

                Log.d("resfffff", "刷卡time"+time);
               /* if (time > 3000 ) {//|| !lastCard.equals(curCard)
                    lastCard = curCard;
                    lastDate =  curDate;
                    Log.d("resfffff", "刷卡成功"+curCard);
                    doExecCard( lastCard );
                }*/


                if (!cardId.equals(factoryFixID)) {//物理卡号不相同，时间不到
                    Log.d("res", "连刷----");
                    startDowntime();

                    return;
                } else {
                    cardId = factoryFixID;
                    Log.d("res", "第一次刷----cardId -16=" + cardId + "cardId-10=");

                    if (!isLoading) {
                        isLoading = true;
                        doExecCard(cardId);
                    } else {
                        Log.d("res", "正在上传中----");
                    }
                }
            }














         /*   String strFix="2941840887";

            if(!TextUtils.isEmpty(strFix)){
                strFix=Long.toHexString(Long.valueOf(strFix));
            }
            if(strFix.equalsIgnoreCase(sb.toString())){
                Log.d("res","刷卡成功");
            }else{
                Log.d("res","刷卡失败");
            }*/


        } else {
            Log.d("res", "获取数据异常--");
        }


        //

        //测试
      /*  List<TLV> mlist= MyFunc.ByteArrToHexBB(ComRecData.bRec);

        String strFix="2941840887";

        if(!TextUtils.isEmpty(strFix)){
            strFix=Long.toHexString(Long.valueOf(strFix));
        }

        if(mlist!=null && mlist.size()>1){
            Log.d("res", mlist.get(1).value);
            if(strFix.equalsIgnoreCase(mlist.get(1).value)){
                Log.d("res","刷卡成功");
            }else{
                Log.d("res","刷卡失败");
            }
        }
        //
        sMsg.append(MyFunc.ByteArrToHex(ComRecData.bRec));


        sMsg.append("\r\n");
*/

    }

    private void doExecCard(String mCardId) {
        Log.d(TAG, "cardInfo:" + mCardId);
        String cardId =  mCardId.trim();
        Log.d(TAG, "cardInfo:fixId" + cardId);
        //测试
       /* if (true) {
            takePicture("1001");
            return;
        }*/
        //

        //Bug
        if (MeetingId == null || MeetingId.size() <= 0) {
            Log.d("TAG", "cardInfo:MeetingId.size()=" + MeetingId.size());
            soundPool1.play(1, 1, 1, 0, 0, 1);
            Toast.makeText(TestMainActivity.this, "刷卡失败！", Toast.LENGTH_SHORT).show();
            return;
        }
        //
        MeetingResutl meetingResutl;
        RealmResults<MeetingResutl> dog = realmHelper.querMeetingResutllById(MeetingId.get(indexBigen));
        if (null != dog && dog.size() > 0) {
            meetingResutl = realmHelper.querMeetingResutll(MeetingId.get(indexBigen));
        } else {
            Log.e("TAG", "dog==null");
            return;
        }

//        MeetingResutl meetingResutl = realmHelper.querMeetingResutll(MeetingId.get(indexBigen));
        Log.d("www", "cardInfo:" + cardId);
        BigenCard = MyApp.getsInstance().getBigenCard();
        if (BigenCard.size() != 0 && indexBigen < BigenCard.size() && indexEnd < EndCard.size()) {
            String Bigen = DatetimeUtil.getDateTimeFromMillisecond(DatetimeUtil.TimeStrToSecond(BigenCard.get(indexBigen)) - 1000 * 60 * (meetingResutl.getInBefore()));
           /* String End = DatetimeUtil.getDateTimeFromMillisecond(
                    DatetimeUtil.TimeStrToSecond(EndCard.get(indexEnd)) + 1000 * 60 * (meetingResutl.getLeaveEarly()));*/
            if (meetingResutl.getNeedCheckout() == 1) {
                End = DatetimeUtil.getDateTimeFromMillisecond(
                        DatetimeUtil.TimeStrToSecond(EndCard.get(indexEnd)) + 1000 * 60 * (meetingResutl.getOutLate()));

            } else {
                End = DatetimeUtil.getDateTimeFromMillisecond(
                        DatetimeUtil.TimeStrToSecond(EndCard.get(indexEnd)));

            }
            List<PersonnelResutl> list = realmHelper.queryDobByAge(MeetingId.get(mSharePreferenceUtil.getIndexBigen()));
            PersonnelResutl mPresult = null;
            Log.w("wwwjjj", "list-size" + list.size());
            boolean isExist = false;
            for (int i = 0; i < list.size(); i++) {
                Log.w("www", "第" + i + "条" + list.get(i).toString());
                if (cardId.equals(list.get(i).getWlkh())) {
                    isExist = true;
                    mPresult = list.get(i);
                    Log.w("www", "物理卡号存在：" + cardId);
                    break;
                }
            }

            if (isExist) {//realmHelper.isDogExist(cardId, MeetingId.get(indexBigen))
                if (DatetimeUtil.TimeCompare(getSysDate("HH:mm"), DatetimeUtil.gethour(Bigen), DatetimeUtil.gethour(End)) && null != mPresult) {
                    int count = realmHelper.queryDogListMeeting(cardId, MeetingId.get(indexBigen)).size();
                    Log.d("www", "count" + count + " cardId" + cardId+"time=="+mPresult.getTime());
                    if (!mPresult.getTime().equals("00:00:00")) {//realmHelper.queryDogListMeeting(cardId, MeetingId.get(indexBigen)).size() == 1
                        Log.d("www", "已签到过");

                        //你已签到过
                        soundPool2.play(1, 1, 1, 0, 0, 1);
                        Toast.makeText(TestMainActivity.this, "您已签到！", Toast.LENGTH_SHORT).show();
                        isLoading = false;

                    } else {
                        Log.d("wwwdddd", "第一次签到"+cardId);
                        if (isSoundReady) {

                            Date(cardId);
                            takePicture(cardId);

                            Toast.makeText(TestMainActivity.this, "刷卡成功！", Toast.LENGTH_LONG).show();

                        }
                    }

                } else {
                    isLoading = false;
                    Toast.makeText(TestMainActivity.this, "您暂时没有需要签到的会议", Toast.LENGTH_SHORT).show();
                    soundPool1.play(1, 1, 1, 0, 0, 1);
                }
            } else {
                isLoading = false;
                Log.d("TAG", "空");
                soundPool1.play(1, 1, 1, 0, 0, 1);
                Toast.makeText(TestMainActivity.this, "您不在该此会议开会", Toast.LENGTH_SHORT).show();
            }
        } else {
            isLoading = false;
            soundPool1.play(1, 1, 1, 0, 0, 1);
            Toast.makeText(TestMainActivity.this, "刷卡失败！", Toast.LENGTH_SHORT).show();
        }


    }

    public void initReGllery() {
        if (null == reGllery) {
            reGllery = new ReGallery_adapter(this, mListR);
            main_gallery.setAdapter(reGllery);
        }

    }

    public void initAttAdapter() {
        if (null == attendanceAdapter) {
            attendanceAdapter = new AttendanceAdapter(TestMainActivity.this, list);
            listView.setAdapter(attendanceAdapter);
        }
        attendanceAdapter.notifyDataSetChanged();

    }

    public void initGallery_adapter() {
        if (null == gallery_adapter) {
            gallery_adapter = new Gallery_adapter(this, li);

        }
        if (null != mListR && null != reGllery) {
            mListR.clear();
            reGllery.notifyDataSetChanged();
        }

        gallery_adapter.notifyDataSetChanged();
        main_gallery.setAdapter(gallery_adapter);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d(TAG, " onRestart()---");
     /* doReadCardSetting();
        loadMusic();*/
        isLoading = false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e(TAG, " onResume()---");

    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.e(TAG, " onPause()---");
    }

    @Override
    protected void onStop() {
        super.onStop();
        TestMainActivity.this.finish();
        Log.e(TAG, " onStop()---");
     /*   if (null != soundPool) {
            soundPool.release();
        }
        if (null != soundPool1) {
            soundPool1.release();
        }
        if (null != soundPool2) {
            soundPool2.release();
        }*/
    }
}

